#!/usr/bin/env python

import re
from ftplib import FTP
from distutils import version
import sys

def findLatest(url):  
	"""Find the latest vercion of a source tarball in a FTP folder. Part \
			vlmigratepackages."""

	# Find what we need from url
	sp = url.rsplit('/')

	# filename
	filename = sp[-1]
	print 'Filename: ' + filename

	# name
	name = filename.rsplit('-', 1)[0]
	print 'Name: ' + name

	# version
	ver = re.match('.*-(.*)\.tar\.[bg]z\d*', filename).group(1)
	print '%s: %s' % ('Version', ver)

	# host
	host = sp[2]
	print 'Host: ' + host

	# dir 
	dir = "/".join(sp[3:-1])

	# ftp connection
	ftp = FTP(host)
	ftp.connect()
	ftp.login()
	ftp.cwd(dir)
	print 'Cwd: ' + ftp.pwd()
	
	# get a remote list of files
	list = ftp.nlst()

	# find the latest
	latest = ver
	for i in list:
		# we need to control in some way that we are comparing versions of the same file
			rname = i.rsplit('-', 1)[0]
			if rname == name and re.match('.*.tar.[bg]z\d*$', i):
				#find version of remote file
				rver = re.match('.*-(.*)\.tar\.[bg]z\d*', i).group(1)
				if version.LooseVersion(rver) > version.LooseVersion(latest):
					latest = rver
					slatest = i

	return 'ftp://%s/%s' % (host, slatest)


if len(sys.argv) != 2:
	sys.stderr.write('USAGE: findLatest.py <URL>\n')
else:
	print 'Latest: ' + findLatest(sys.argv[1])

# Example: ./findLatestFtp.py ftp://ftp.bitwizard.nl/mtr/mtr-0.21.tar.gz
# vim: set tabstop=4 shiftwidth=4 foldmethod=marker : ##
